import json
import sys
from sqlalchemy.orm import Session

sys.path.append('..')

from database.db import get_db, engine, Base
from models.detection_target import DetectionTarget

# 预设检测目标数据
PRESET_TARGETS = [
    # 基础目标
    {
        "name": "人员",
        "description": "检测场景中的人员",
        "target_type": "person",
        "properties": {
            "min_size": 10,
            "max_size": 100,
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "车辆",
        "description": "检测场景中的车辆",
        "target_type": "vehicle",
        "properties": {
            "min_size": 20,
            "max_size": 200,
            "confidence_threshold": 0.6
        }
    },
    {
        "name": "建筑物",
        "description": "检测场景中的建筑物",
        "target_type": "building",
        "properties": {
            "min_size": 50,
            "max_size": 500,
            "confidence_threshold": 0.5
        }
    },
    {
        "name": "道路",
        "description": "检测场景中的道路",
        "target_type": "road",
        "properties": {
            "min_width": 5,
            "min_length": 20,
            "confidence_threshold": 0.6
        }
    },
    {
        "name": "水域",
        "description": "检测场景中的水域",
        "target_type": "water",
        "properties": {
            "min_area": 100,
            "confidence_threshold": 0.5
        }
    },
    # 电力巡检目标
    {
        "name": "线路断裂",
        "description": "高压线路断裂情况",
        "target_type": "power_line_defect",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.8
        }
    },
    {
        "name": "绝缘子缺陷",
        "description": "绝缘子破损或异常情况",
        "target_type": "power_line_defect",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.75
        }
    },
    {
        "name": "塔材腐蚀",
        "description": "铁塔材料腐蚀情况",
        "target_type": "power_line_defect",
        "properties": {
            "detection_priority": "medium",
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "异物悬挂",
        "description": "线路上的异物悬挂",
        "target_type": "power_line_defect",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.8
        }
    },
    {
        "name": "导线弧垂异常",
        "description": "导线弧垂不正常情况",
        "target_type": "power_line_defect",
        "properties": {
            "detection_priority": "medium",
            "confidence_threshold": 0.75
        }
    },
    # 管道检测目标
    {
        "name": "管道泄漏",
        "description": "管道泄漏点",
        "target_type": "pipeline_defect",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.8,
            "thermal_detection": True
        }
    },
    {
        "name": "地面渗透",
        "description": "地面液体渗透痕迹",
        "target_type": "pipeline_defect",
        "properties": {
            "detection_priority": "medium",
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "植被异常",
        "description": "因泄漏导致的植被异常",
        "target_type": "pipeline_defect",
        "properties": {
            "detection_priority": "low",
            "confidence_threshold": 0.6
        }
    },
    {
        "name": "设备腐蚀",
        "description": "管道设备腐蚀情况",
        "target_type": "pipeline_defect",
        "properties": {
            "detection_priority": "medium",
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "阀门损坏",
        "description": "管道阀门损坏情况",
        "target_type": "pipeline_defect",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.8
        }
    },
    # 应急救援目标
    {
        "name": "人员定位",
        "description": "需要救援的人员位置",
        "target_type": "rescue_target",
        "properties": {
            "detection_priority": "highest",
            "confidence_threshold": 0.6
        }
    },
    {
        "name": "被困人员",
        "description": "被困在危险区域的人员",
        "target_type": "rescue_target",
        "properties": {
            "detection_priority": "highest",
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "火势蔓延",
        "description": "火灾蔓延情况",
        "target_type": "rescue_hazard",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.8,
            "thermal_detection": True
        }
    },
    {
        "name": "危险区域",
        "description": "需要避开的危险区域",
        "target_type": "rescue_hazard",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.75
        }
    },
    {
        "name": "道路阻断",
        "description": "被阻断的道路",
        "target_type": "rescue_hazard",
        "properties": {
            "detection_priority": "medium",
            "confidence_threshold": 0.7
        }
    },
    # 环保监测目标
    {
        "name": "水体污染",
        "description": "水体污染情况",
        "target_type": "environmental_hazard",
        "properties": {
            "detection_priority": "high",
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "植被覆盖",
        "description": "植被覆盖情况",
        "target_type": "environmental_monitor",
        "properties": {
            "detection_priority": "low",
            "confidence_threshold": 0.6,
            "ndvi_required": True
        }
    },
    {
        "name": "烟气排放",
        "description": "工厂烟气排放",
        "target_type": "environmental_hazard",
        "properties": {
            "detection_priority": "medium",
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "垃圾堆积",
        "description": "非法垃圾堆积",
        "target_type": "environmental_hazard",
        "properties": {
            "detection_priority": "medium",
            "confidence_threshold": 0.7
        }
    },
    {
        "name": "野生动物监测",
        "description": "野生动物活动监测",
        "target_type": "environmental_monitor",
        "properties": {
            "detection_priority": "low",
            "confidence_threshold": 0.65
        }
    }
]

def init_detection_targets():
    """初始化检测目标数据"""
    # 创建表（如果不存在）
    Base.metadata.create_all(bind=engine)
    
    # 获取数据库会话
    db = next(get_db())
    
    try:
        # 检查是否已有数据
        existing_targets = db.query(DetectionTarget).all()
        existing_target_names = {target.name for target in existing_targets}
        
        # 插入预设数据，只添加不存在的目标
        new_targets_count = 0
        for target_data in PRESET_TARGETS:
            if target_data["name"] not in existing_target_names:
                target = DetectionTarget(
                    name=target_data["name"],
                    description=target_data["description"],
                    target_type=target_data["target_type"],
                    properties=json.dumps(target_data["properties"])
                )
                db.add(target)
                new_targets_count += 1
        
        # 提交事务
        db.commit()
        
        print(f"检测目标数据更新成功，共添加 {new_targets_count} 条新记录")
        
    except Exception as e:
        print(f"初始化检测目标数据时出错: {e}")
        db.rollback()
    finally:
        db.close()


if __name__ == "__main__":
    init_detection_targets()